<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import {
  deleteBatch,
  deleteUser,
  edit,
  exp,
  generateImportTemplate,
  importExcel,
  list,
  save,
  selectUserByUserId
} from "@/api/user";
import {findAll} from "@/api/role";
export default {
  name: "User",
  components:{ElImageViewer},
  data() {
    return {
      userId: null,
      id: null,
      userName: null,
      phonenumber: null,
      email: null,
      address: null,
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      visible: false,
      loading: true,
      multipleSelection: [],
      dialogFormVisible: false,
      dialogFormVisible1: false,
      importDialogVisible: false,
      form: {},
      formLabelWidth: '70px',
      options: [],
      showViewer:false,
      avatarList:[],
      fileList:[]
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
       let params= {
          userId: this.userId,
          userName: this.userName,
          phonenumber: this.phonenumber,
          email: this.email,
          address: this.address,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        }
      list(params).then(res => {
        this.tableData = res.data.records;
        this.loading = false;
        this.total = res.data.total;

      });

    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();

    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.load();
    },
    reset() {
      this.userId = null;
      this.userName = null;
      this.phonenumber = null;
      this.email = null;
      this.address = null;
      this.tableData = [];
      this.currentPage = 1;
      this.pageSize = 5;
      this.total = 0;
      this.load();
    },
    handleDelete(id) {
      deleteUser(id).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.load();
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
          this.load();
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((a) => a.userId);
      console.log(this.multipleSelection);
    },
    handleBatchRemove() {
      let ids = this.multipleSelection;
     deleteBatch(ids).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            center: true
          });
          this.currentPage=this.currentPage-1;
          this.load();
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
          this.load();
        }
      })
    },
    handleEdit(id) {
      this.id = id;
     findAll().then(res => {
        this.options = res.data;
      });
      selectUserByUserId(this.id).then(res => {
        this.form = res.data;
        this.form.status = '' + res.data.status;
      });
      this.dialogFormVisible = true;
    },
    handleSave() {
      this.dialogFormVisible1 = true;
      this.form = {};
      findAll().then(res => {
        this.options = res.data;
      })
    },
    save() {
     save(this.form).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '用户创建成功',
            type: 'success',
            center: true
          });
          this.dialogFormVisible1 = false;
          this.form = {};
          this.load();
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
          this.dialogFormVisible1 = false;
          this.form = {};
        }
      })
    },
    edit() {
      edit(this.id,this.form).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '用户信息修改成功',
            type: 'success',
            center: true
          });
          this.dialogFormVisible = false;
          this.load();
          this.form = {};
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
          this.dialogFormVisible = false;
          this.form = {};
        }
      })
    },
    sex(row) {
      if (row.sex == 0) {
        return "男";
      } else if (row.sex == 1) {
        return "女";
      } else {
        return "未知";
      }
    },
    filterStatus(value, row) {
      return row.status === value;
    },
    headerBg({row, rowIndex}) {
      if (rowIndex == 0) {
        return 'headerBgClass';
      }
    },
    showViewerClose(){
      this.showViewer=false;
    },
    getViewer(avatar){
      if(avatar){
        this.avatarList=[];
        this.avatarList.push(avatar);
        this.showViewer=true;
      }else{
        this.$message.error("该用户未设置头像");
      }
   },
    exp(){
     exp().then(res=>{
        console.log(res)
        const blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" })
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = decodeURI(
        res.headers["content-disposition"].split("filename=")[1]);
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      })
    },
    downloadTemplate(){
     generateImportTemplate().then(res=>{
        console.log(res)
        const blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" })
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = decodeURI(
            res.headers["content-disposition"].split("filename=")[1]);
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      })
    },
    beforeImportExcel(file){
      const isXlsx=/\.(xls|xlsx)$/.test(file.name.toLowerCase());
      if(!isXlsx){
        this.$message.error("仅允许导入xls、xlsx格式文件。");
      }
      return isXlsx;
    },
    submitImport(){
      this.$refs.upload.submit();
    },
    importExcel(param){
      let file=param.file;
      const isXlsx=/\.(xls|xlsx)$/.test(file.name.toLowerCase());
      if(!isXlsx){
        this.$message.error("仅允许导入xls、xlsx格式文件,导入失败。");
        return;
      }
     let formData=new FormData();
     formData.append("file",file);
     importExcel(formData).then(res=>{
       this.fileList=[];
       if(res.code===200){
         this.importDialogVisible=false;
         this.$message({
           message: '用户信息导入成功',
           type: 'success',
           center: true
         });
         this.load();
       }else{
         this.importDialogVisible=false;
         this.$message({
           message: '用户信息导入失败',
           type: 'error',
           center: true
         });
       }
     })
    }
  }

}
</script>

<template>
  <div>
    <div>
      <el-input style="width:120px" suffix-icon="el-icon-search" placeholder="请输入用户ID" v-model="userId"></el-input>
      <el-input style="width:140px" suffix-icon="el-icon-search" placeholder="请输入用户名称" v-model="userName"
                class="ml-5"></el-input>
      <el-input style="width:140px" suffix-icon="el-icon-phone" placeholder="请输入手机号码" v-model="phonenumber"
                class="ml-5"></el-input>
      <el-input style="width:140px" suffix-icon="el-icon-message" placeholder="请输入用户邮箱" v-model="email"
                class="ml-5"></el-input>
      <el-input style="width:140px" suffix-icon="el-icon-position" placeholder="请输入联系地址" v-model="address"
                class="mlr-5"></el-input>
      <el-button type="primary" class="ml-5" @click="load">搜索</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="reset">重置</el-button>
    </div>
    <div style="margin:10px 0px">
      <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleSave">新增</el-button>
      <el-dialog title="创建用户信息" :visible.sync="dialogFormVisible1" width="25%" center>
        <el-form :model="form">
          <el-form-item label="用户名称" :label-width="formLabelWidth">
            <el-input v-model="form.userName" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" :label-width="formLabelWidth">
            <el-input v-model="form.nickName" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户密码" :label-width="formLabelWidth">
            <el-input v-model="form.password" autocomplete="off" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="用户角色" :label-width="formLabelWidth">
            <el-select v-model="form.role" placeholder="请选择">
              <el-option
                  v-for="item in options"
                  :key="item.flag"
                  :label="item.roleName"
                  :value="item.flag">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户性别" :label-width="formLabelWidth">
            <el-radio v-model="form.sex" label="0">男</el-radio>
            <el-radio v-model="form.sex" label="1">女</el-radio>
            <el-radio v-model="form.sex" label="2">未知</el-radio>
          </el-form-item>
          <el-form-item label="用户邮箱" :label-width="formLabelWidth">
            <el-input v-model="form.email" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机号码" :label-width="formLabelWidth">
            <el-input v-model="form.phonenumber" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="联系地址" :label-width="formLabelWidth">
            <el-input v-model="form.address" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户状态" :label-width="formLabelWidth">
            <el-radio v-model="form.status" label="1">正常</el-radio>
            <el-radio v-model="form.status" label="0">停用</el-radio>
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入内容"
                v-model="form.remark" clearable>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="save">确 定</el-button>
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        </div>
      </el-dialog>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="你确定批量删除吗？"
          @confirm="handleBatchRemove"
          class="ml-5"
      >
        <el-button type="danger" icon="el-icon-remove-outline" slot="reference">批量删除</el-button>
      </el-popconfirm>
      <el-button type="primary" icon="el-icon-download" style="margin-left: 5px" @click="downloadTemplate">下载模版</el-button>
      <el-button type="primary" icon="el-icon-bottom" style="margin-left: 5px" plain @click="importDialogVisible=true">导入</el-button>
      <el-dialog :visible.sync="importDialogVisible" title="用户导入"  :width="'400px'" >
        <el-upload
            class="upload-demo"
            ref="upload"
            action="#"
            drag
            :limit="1"
            :file-list="fileList"
            :http-request="importExcel"
            :auto-upload="false"
            :multiple="false"
            :before-upload="beforeImportExcel"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip" style="text-align: center">仅允许导入xls、xlsx格式文件。<el-button type="text" @click="downloadTemplate">下载模版</el-button></div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitImport">确 定</el-button>
          <el-button @click="importDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-button type="primary" icon="el-icon-top" style="margin-left: 5px" @click="exp" plain>导出</el-button>
    </div>
    <el-table :data="tableData"
              border stripe
              :header-cell-class-name="headerBg"
              max-height="550"
              v-loading="loading"
              ref="filterTable"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255,225,255, 0.1)"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55px" align="center"></el-table-column>
      <el-table-column prop="userId" label="用户ID" width="100px" sortable align="center">
      </el-table-column>
      <el-table-column prop="userName" label="用户名称" width="100px" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="100px" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column label="头像" width="100px" align="center">
        <template slot-scope="scope">
          <el-image-viewer v-if="showViewer" :on-close="showViewerClose" :url-list="avatarList"></el-image-viewer>
          <el-button type="primary" @click="getViewer(scope.row.avatar)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="用户角色" width="100px" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column prop="sex" label="用户性别" width="70px" :formatter="sex" :show-overflow-tooltip=true
                       align="center">
      </el-table-column>
      <el-table-column prop="phonenumber" label="手机号码" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column prop="email" label="用户邮箱" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column prop="address" label="联系地址" width="100px" :show-overflow-tooltip=true align="center">
      </el-table-column>
      <el-table-column prop="status" label="状态" width="70px" :filters="[{text:'正常',value:1},{text:'停用',value:0}]"
                       :filter-method="filterStatus" filter-placement="bottom-end" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ?'success':'danger'">
            {{ scope.row.status === 1 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template slot-scope="scope">
          <el-button type="success" icon="el-icon-edit" @click="handleEdit(scope.row.userId)">编辑</el-button>
          <el-dialog title="修改用户信息" :visible.sync="dialogFormVisible" width="25%" center>
            <el-form :model="form">
              <el-form-item label="用户名称" :label-width="formLabelWidth">
                <el-input v-model="form.userName" autocomplete="off" disabled clearable></el-input>
              </el-form-item>
              <el-form-item label="用户昵称" :label-width="formLabelWidth">
                <el-input v-model="form.nickName" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item label="用户角色" :label-width="formLabelWidth">
                <el-select v-model="form.role" placeholder="请选择">
                  <el-option
                      v-for="item in options"
                      :key="item.flag"
                      :label="item.roleName"
                      :value="item.flag">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="用户性别" :label-width="formLabelWidth">
                <el-radio v-model="form.sex" label="0">男</el-radio>
                <el-radio v-model="form.sex" label="1">女</el-radio>
                <el-radio v-model="form.sex" label="2">未知</el-radio>
              </el-form-item>
              <el-form-item label="用户邮箱" :label-width="formLabelWidth">
                <el-input v-model="form.email" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item label="手机号码" :label-width="formLabelWidth">
                <el-input v-model="form.phonenumber" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item label="联系地址" :label-width="formLabelWidth">
                <el-input v-model="form.address" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item label="用户状态" :label-width="formLabelWidth">
                <el-radio v-model="form.status" label="1">正常</el-radio>
                <el-radio v-model="form.status" label="0">停用</el-radio>
              </el-form-item>
              <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入内容"
                    v-model="form.remark" clearable>
                </el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="edit">确 定</el-button>
              <el-button @click="dialogFormVisible = false">取 消</el-button>
            </div>
          </el-dialog>
          <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="你确定删除吗？"
              @confirm="handleDelete(scope.row.userId)"
              class="ml-5"
          >
            <el-button type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding:10px 0px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.headerBgClass {
  background-color: #cccccc !important;
}
</style>
